﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using A2DFramework.AOPService.Core;
using A2DFramework.InstanceService;

namespace A2DFramework.Repository
{
    public class GenericRepository : IRepository
    {
        internal DbContext context = ObjectFactory.Resolve<DbContext>();

        public virtual IEnumerable<T> Get<T>(
            Expression<Func<T, bool>> filter = null,
            Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
            string includeProperties = "")
            where T:class
        {
            IQueryable<T> query = context.Set<T>();

            
            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public virtual T GetByID<T>(object id)
            where T : class
        {
            return context.Set<T>().Find(id);
        }

        public virtual void Insert<T>(T entity)
            where T : class
        {
            context.Set<T>().Add(entity);
        }

        public virtual void Delete<T>(object id)
            where T : class
        {
            T entityToDelete = context.Set<T>().Find(id);
            Delete(entityToDelete);
        }

        public virtual void Delete<T>(T entityToDelete)
            where T : class
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                context.Set<T>().Attach(entityToDelete);
            }
            context.Set<T>().Remove(entityToDelete);
        }

        public virtual void Update<T>(T entityToUpdate)
            where T : class
        {
            context.Set<T>().Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }

        public virtual IEnumerable<T> GetWithRawSql<T>(string query, params object[] parameters)
            where T : class
        {
            return context.Set<T>().SqlQuery(query, parameters).ToList();
        }


        public void Save()
        {
            context.SaveChanges();
        }
    }
}
